package com.zhilian.hzrf_oa.mvp.main.model;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.colin.constant.Constants;
import com.colin.http.HttpServiceManager;
import com.colin.http.HttpUtil;
import com.colin.utils.LogUtil;
import com.google.gson.Gson;
import com.zhilian.hzrf_oa.bean.UpdateBean;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by colin on 2018/2/27 8:54 .
 */

public class MainModel implements IMainModel {
	int localVersion = 0;
	String localName = "";
	@Override
	public void checkVersion(Context context, Callback callback) {

		//获取本地版本号
		try {
			PackageInfo packageInfo = context.getApplicationContext()
				.getPackageManager()
				.getPackageInfo(context.getPackageName(), 0);
			localVersion = packageInfo.versionCode;
			localName = packageInfo.versionName;
			LogUtil.d("本软件的版本号。。" + localVersion);
			LogUtil.d("本软件的版本。。" + localName);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		//获取远程版本号
		Map<String,String> map = new HashMap<>();
		map.put("app_type", String.valueOf(1));// 这里传的是类型 0: ios  1: android
		HttpServiceManager.getInstance()
			.getHttpService()
			.getServerData(HttpUtil.initUrl(), HttpUtil.initQueryParams(Constants.TYPE_QUERY, Constants.QUERY_VERSION, map))
			.subscribeOn(Schedulers.newThread())
			.observeOn(AndroidSchedulers.mainThread())
			.subscribe(new Consumer<ResponseBody>() {
				@Override
				public void accept(@NonNull ResponseBody responseBody) throws Exception {
					UpdateBean model = new Gson().fromJson(responseBody.string(), UpdateBean.class);
					// 判断服务版本号是否大于当前版本号
					String[] arr = model.getVersion_code().split("\\.");

					int version_code = Integer.parseInt(arr[arr.length-1]);
					if (version_code>localVersion){
						callback.onCheckVersion(model);
					}
				}
			}, new Consumer<Throwable>() {
				@Override
				public void accept(Throwable throwable) throws Exception {
					LogUtil.e(throwable.getMessage());
				}
			});

	}
}
